import {
	CallHandler,
	ExecutionContext,
	Injectable,
	NestInterceptor,
} from "@nestjs/common";
import { Observable, map } from "rxjs";
import { ResultCodeEnum } from "../enums/resultCode.enum";
import { LoggerService } from "@/common/logger/logger.service";

@Injectable()
export class TransformInterceptor implements NestInterceptor {
	constructor(private readonly logger: LoggerService) {}
	intercept(context: ExecutionContext, next: CallHandler): Observable<any> {
		const request = context.switchToHttp().getRequest();
		// 去掉字符串两端的空格
		if (request.body) {
			this.trimStrings(request.body);
		}
		return next.handle().pipe(
			map((data) => {
				const result = {
					code: ResultCodeEnum.SUCCESS,
					message: data?.message || "success",
					data: data?.data || data,
				};
				// 记录日志
				this.logger.setContext(context.getClass().name);
				this.logger.log(JSON.stringify(result));
				return result;
			}),
		);
	}

	private trimStrings(data: any): any {
		if (data instanceof Object) {
			Object.keys(data).forEach((key) => {
				if (typeof data[key] === "string") {
					data[key] = data[key].trim() || undefined;
				} else if (data[key] instanceof Object) {
					this.trimStrings(data[key]);
				}
			});
		}
	}
}
